﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.IsolatedStorage;
using RSSReader.MobileClient.Model;
using System.ComponentModel;
using System.Net;
using System.Xml.Linq;
using System.Windows.Input;
using RSSReader.MobileClient.Framework;

namespace RSSReader.MobileClient.ViewModel
{
    class FeedViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Feed> Feeds { get; set; }
        public AsyncDataManager AsyncDM { get; set; }
        public AsyncDataManager AsyncDMCheck { get; set; }
        public AsyncDataManager AsyncDMDel { get; set; }
        //public ObservableCollection<string> Subs = new ObservableCollection<string>();
        public WCFWebRoleService.DataDistributorClient CurrentFeeds = new WCFWebRoleService.DataDistributorClient();
        public ObservableCollection<WCFWebRoleService.UserSubscriptionInformation> Subscriptions;
        public bool LegitFeed = true;
        public string CurOriginFeed;
        private ICommand deleteDataCommand;

        public FeedViewModel()
        {
            deleteDataCommand = new DelegateCommand(DeleteDataAction);
        }

        public ICommand DeleteDataCommand
        {
            get
            {
                return deleteDataCommand;
            }
        }

        public void DeleteDataAction(object p)
        {

        }

        public void DelFeed(string url, string id)
        {   
            ObservableCollection<string> _url = new ObservableCollection<string>();

            _url.Add(url);
            CurrentFeeds.RemoveSubscriptionsAsync(_url, id);
        }

        public void GetFeeds(AsyncDataManager b)
        {
            AsyncDM = b;

            GetDefaultFeeds();
        }

        public void GetDefaultFeeds()
        {
            ObservableCollection<Feed> a = new ObservableCollection<Feed>();
            CurrentFeeds.GetSubscriptionsCompleted += new EventHandler<WCFWebRoleService.GetSubscriptionsCompletedEventArgs>(CallBackUserSubscription);
            CurrentFeeds.GetSubscriptionsAsync(App.UserId);

            //Feeds = a;
        }

        private void CallBackUserSubscription(object sender, WCFWebRoleService.GetSubscriptionsCompletedEventArgs e)
        {
            Subscriptions = new ObservableCollection<WCFWebRoleService.UserSubscriptionInformation>();
            Subscriptions = e.Result;
            AssignSubsToFeeds();
        }

        private void AssignSubsToFeeds()
        {
            ObservableCollection<Feed> a = new ObservableCollection<Feed>();
            string ConcatURL = "";
            int i = 0;

            foreach (WCFWebRoleService.UserSubscriptionInformation USI in Subscriptions)
            {
                a.Add(new Feed() { Link = "/ArticlePage.xaml?LocLink=" + USI.Url, FeedName = USI.Title, deleteLink = "/ActionPage.xaml?DeleteFeed=" + USI.Url });
                ConcatURL += "Url" + i.ToString() + "=" + USI.Url + "&";
                i++;
            }
            a.Insert(0, new Feed() { Link = "/ArticlePage.xaml?LocLink=All&" + ConcatURL, FeedName = "All Feeds"});
            Feeds = a;
            AsyncDM.ManageCallbacks("GotSubscriptions");
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void GetSavedFeeds()
        {
            ObservableCollection<Feed> a = new ObservableCollection<Feed>();

            foreach (Object o in IsolatedStorageSettings.ApplicationSettings.Values)
            {
                a.Add((Feed)o);
            }
        }

        public void AddFeed(ObservableCollection<WCFWebRoleService.UserSubscriptionInformation> NewSubs)
        {
            if (NewSubs.Count > 0)
            {
                if (LegitFeed == true)
                {
                    NewSubs[0].Title = CurOriginFeed;
                    CurrentFeeds.SetSubscriptionsAsync(NewSubs, App.UserId);
                }
            }
        }

        public void CheckFeedValidity(string url, AsyncDataManager a)
        {
            AsyncDMCheck = a;
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            try
            {
                wc.DownloadStringAsync(new Uri(url));
            }
            catch
            {
                AsyncDMCheck.ManageCallbacks("CheckedFeed");
                LegitFeed = false;
            }
            
        }

        private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                XElement xmlitems = XElement.Parse(e.Result);
                List<XElement> feedinfo = xmlitems.Descendants("channel").ToList();
                AsyncDMCheck.ManageCallbacks("CheckedFeed");
                CurOriginFeed = feedinfo[0].Element("title").Value;
            }
            catch
            {
                LegitFeed = false;
                AsyncDMCheck.ManageCallbacks("CheckedFeed");
                return;
            }
        }
    }
}
